package finger.dao.impl;

import finger.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao {
    QueryRunner queryRunner = new QueryRunner();

    public int update(String sql, Object... args) {
        Connection con = JDBCUtils.getConnection();
        try {

            return queryRunner.update(con, sql, args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);

        }

    }

    public <T> T getQueryForOne(Class<T> type, String sql, Object... args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            return queryRunner.query(con, sql, new BeanHandler<T>(type), args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);

        }
    }

    public <T> List<T> getQueryForList(Class<T> type, String sql, Object... args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            return queryRunner.query(con, sql, new BeanListHandler<T>(type),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);

        }
    }
    public Object queryForSingleValue(String sql,Object...obj){
        Connection conn = JDBCUtils.getConnection();
        try {
            return queryRunner.query(conn,sql,new ScalarHandler(),obj);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);

        }
    }
}
